package pl.jtb.ctl.tabory.ui.boe.ui.he;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.widgets.Section;

import pl.jtb.ctl.tabory.dao.api.services.IVagonService;
import pl.jtb.ctl.tabory.dao.data.vo.TripVO;
import pl.jtb.ctl.tabory.dao.data.vo.VagonVO;
import pl.jtb.ctl.tabory.dao.impl.mybatis.servicemanager.ServiceManager;
import pl.jtb.ctl.tabory.ui.boe.osgi.Activator;
import pl.jtb.ctl.tabory.ui.boe.selection.HistoricalDataSelection;
import pl.jtb.ctl.tabory.ui.boe.selection.TripSelection;
import pl.jtb.ctl.tabory.ui.boe.selection.VagonSelection;
import pl.jtb.ctl.tabory.ui.boe.ui.te.TripDialog;
import pl.jtb.ctl.tabory.ui.boe.ui.te.TripSection;
import pl.jtb.ctl.tabory.ui.boe.ui.ve.VagonMasterSectionPart;
import pl.jtb.ctl.tabory.ui.boe.ui.ve.VagonMasterSectionPart.AvailableColumnsSL;
import pl.jtb.ctl.tabory.ui.editors.AbstractEditorPart;
import pl.jtb.ctl.tabory.ui.editors.EditorStateSL;
import pl.jtb.ctl.tabory.ui.selection.ISelectionListener;

public class HistoricalDataEditor extends AbstractEditorPart<HistoricalDataSelection> {

    public static final String ID = "pl.jtb.ctl.tabory.ui.boe.ui.he.HistoricalDataEditor";
    private final static Logger logger = Logger.getLogger(HistoricalDataEditor.class);

    protected Action editorNewAction;
    protected Action editorEditAction;
    protected Action editorDeleteAction;

    private VagonMasterSectionPart vagonSection;
    private TripSection tripSection;
    private TripSelection tripSelection;

    private VagonSelection vagonSelection;

    public HistoricalDataEditor() throws Exception {
        super();
    }

    public void doNew() {
    }

    private void doEdit() {
    }

    private void doDelete() {
    }

    @Override
    public void createPartControl(Composite parent) {
        super.createPartControl(parent);
        form.getToolBarManager().removeAll();
        form.getToolBarManager().add(editorNewAction);
        form.getToolBarManager().add(editorEditAction);
        form.getToolBarManager().add(editorDeleteAction);
        form.getToolBarManager().update(true);
    }

    @Override
    protected void createActions() {
        super.createActions();
        editorNewAction = new EditorActionNew();
        editorEditAction = new EditorActionEdit();
        editorDeleteAction = new EditorActionDelete();
        editorNewAction.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_TOOL_NEW_WIZARD));
        editorEditAction.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_TOOL_COPY));
        editorDeleteAction.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_TOOL_DELETE));
    }

    @Override
    protected void initGui(Composite parent) {
        GridLayoutFactory.fillDefaults().numColumns(2).margins(5, 5).applyTo(form.getBody());

        Composite container = formToolkit.createComposite(form.getBody(), SWT.NONE);
        GridLayoutFactory.fillDefaults().numColumns(2).applyTo(container);
        GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, true).applyTo(container);

        SashForm leftComposite = new SashForm(container, SWT.VERTICAL);
        GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, true).applyTo(leftComposite);
        formToolkit.paintBordersFor(leftComposite);
        formToolkit.adapt(leftComposite);

        Set<AvailableColumnsSL> columnSet = new HashSet<VagonMasterSectionPart.AvailableColumnsSL>();
        columnSet.add(AvailableColumnsSL.COLUMN_VAGON_NAME);
        vagonSection = new VagonMasterSectionPart(leftComposite, formToolkit, Section.TITLE_BAR, Activator.getMessage("historicaldata.editor.vagonsection.title"), false, true, columnSet);
        GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(false, true).applyTo(vagonSection.getSection());

        SashForm rightComposite = new SashForm(container, SWT.VERTICAL);
        GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, true).applyTo(rightComposite);
        formToolkit.paintBordersFor(rightComposite);
        formToolkit.adapt(rightComposite);

        tripSection = new TripSection(rightComposite, formToolkit, Section.TITLE_BAR, Activator.getMessage("historicaldata.editor.tripsection.title"));
        GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, true).applyTo(tripSection.getSection());
    }

    @Override
    protected void postInitGui(Composite parent) {
        updateButtons();
        vagonSection.addSelectionListener(new VagonPartSelectionListener());
        tripSection.addSelectionListener(new TripPartSelectionListener());
        vagonSection.setSelection(vagonSelection);
        tripSection.setSelection(tripSelection);
    }

    @Override
    protected void doSave() throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    protected void doCancel() throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    protected HistoricalDataSelection initSelection() throws Exception {
        vagonSelection = new VagonSelection();
        tripSelection = new TripSelection();

        vagonSelection.setEditorState(EditorStateSL.CLEAN);

        IVagonService vagonService = ServiceManager.getInstance().getVagonService();
        List<VagonVO> listVagons = vagonService.getListAllVagons();

        vagonSelection.setListVagons(listVagons);

        HistoricalDataSelection selection = new HistoricalDataSelection();
        selection.setListVagons(listVagons);
        return selection;
    }
    
    private void updateSelection() {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void setFocus() {
        setDirty(true);
        editorCancelAction.run();
    }

    private void updateButtons() {
        editorNewAction.setEnabled(false);
        editorEditAction.setEnabled(false);
        editorDeleteAction.setEnabled(tripSelection.getSelectedTrip() != null);
    }

    private class EditorActionNew extends Action {

        public EditorActionNew() {
            super(Activator.getMessage("trip.editor.toolbar.new"));
        }

        @Override
        public void run() {
            logger.debug("Run menu action: new element.");
            BusyIndicator.showWhile(form.getDisplay(), new Runnable() {
                @Override
                public void run() {
                    try {
                        doNew();
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                        openErrorDialog(e);
                    }
                }
            });
        }

    }

    private class EditorActionEdit extends Action {

        public EditorActionEdit() {
            super(Activator.getMessage("trip.editor.toolbar.edit"));
        }

        @Override
        public void run() {
            logger.debug("Run menu action: edit element.");
            BusyIndicator.showWhile(form.getDisplay(), new Runnable() {
                @Override
                public void run() {
                    try {
                        doEdit();
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                        openErrorDialog(e);
                    }
                }
            });
        }
    }

    private class EditorActionDelete extends Action {

        public EditorActionDelete() {
            super(Activator.getMessage("trip.editor.toolbar.delete"));
        }

        @Override
        public void run() {
            logger.debug("Run menu action: delete element.");
            BusyIndicator.showWhile(form.getDisplay(), new Runnable() {
                @Override
                public void run() {
                    try {
                        doDelete();
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                        openErrorDialog(e);
                    }
                }
            });
        }
    }

    private class VagonPartSelectionListener implements ISelectionListener<VagonSelection> {

        @Override
        public void selectionChanged(VagonSelection sel) {
            VagonVO selectedVagon = sel.getSelectedVagon();
            if (selectedVagon != null) {
                List<TripVO> listTripsForVagon;
                try {
                    listTripsForVagon = ServiceManager.getInstance().getTripService().getTripsForVagon(selectedVagon.getId());
                    vagonSelection.setSelectedVagon(selectedVagon);
                    selection.setSelectedVagon(selectedVagon);
                    tripSelection.setListTrips(listTripsForVagon);
                    tripSelection.setSelectedTrip(null);
                    tripSection.setSelection(tripSelection);
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
            updateButtons();
        }

    }

    private class TripPartSelectionListener implements ISelectionListener<TripSelection> {

        @Override
        public void selectionChanged(final TripSelection selection) {
            BusyIndicator.showWhile(Display.getDefault(), new Runnable() {
                @Override
                public void run() {
                    if (selection.getSelectedTrip() != null) {
                        vagonSelection.setListVagons(selection.getSelectedTrip().getListVagons());
                    }
                    updateButtons();
                }
            });
        }

    }

}
